<template>
  <el-form ref="formRuleRef" :model="form" style="margin-top:1em" class="form" :rules="formRules">
    <el-form-item label="班级名" prop="className">
      <el-input placeholder="最长30个字" v-model="form.className"></el-input>
    </el-form-item>
    <el-form-item>
      <div style="width: 100%;display: flex;flex-direction: row;justify-content: center">
        <el-button @click="createExam(formRuleRef)" type="primary" style="width: 39%">创建</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {User} from "../../../types/mytypes";
import {ClassRequest} from "../../../request/MyRequset";
import {UserStore} from "../../../store/store";
import {FormInstance, FormRules} from "element-plus";
const emit = defineEmits(['onClose','error'])
const formRuleRef = ref<FormInstance>();
const formRules = reactive<FormRules>({
  className: [
    {required: true, message: "请输入班级名"},
    {min: 3, max: 30, message: "班级名的长度需在3-30之间"}
  ]
})
const form = reactive({
  className: '',
});
let user: User = reactive({} as User)

onMounted(async () => {
  user = UserStore.getUser();
})

const createExam = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let addClassRes = await ClassRequest.add(user.id,form.className);
      if(addClassRes.suc){
        emit("onClose")
      }else{
        emit('error',addClassRes.message)
      }
    } else {
      console.log("验证不通过")
    }
  })
}
</script>

<style scoped lang="scss">
.form {
  display: flex;
  flex-direction: column;
  align-items: center;

  .el-form-item {
    width: 35em;

    .el-form-item__content {
      justify-content: center;
    }
  }

}

</style>